package com.kll.tv.views.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.kll.carolinehmibiz.AccountManager
import com.kll.carolinehmibiz.net.bean.LoginResponse
import com.kll.tv.R
import com.kll.tv.databinding.ItemSwitchAccountBinding

class SwitchAccountAdapter(var context: Context) : RecyclerView.Adapter<SwitchAccountAdapter.InnerHolder>() {
    private var mItemClickListener: OnAccountListItemClickListener? = null

    // 数据
    var data: MutableList<LoginResponse> = ArrayList()
        set(value) {
            if (value == null) {
                data.clear()
            } else {
                field = value
            }
            notifyDataSetChanged()
        }

    fun addData(data: ArrayList<LoginResponse>) {
        if (data != null) {
            this.data.addAll(data)
            notifyDataSetChanged()
        }
    }

    inner class InnerHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var binding = ItemSwitchAccountBinding.bind(itemView)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): InnerHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.item_switch_account, parent, false)
        return InnerHolder(view)
    }

    override fun onBindViewHolder(holder: InnerHolder, position: Int) {
        val data = data[position]

        // item可以获得焦点，需要设置这个属性。
        holder.itemView.setFocusable(true)

        var avatar = if(data.user!!.head_pic.isNotEmpty() && data.user!!.head_pic.indexOf("?") > 0) data.user!!.head_pic.substring(0, data.user!!.head_pic.indexOf("?")) else ""
        Glide.with(holder.itemView).load("http://${avatar}")
            .apply(RequestOptions().placeholder(R.drawable.icon_contact_family_head))
            .into(holder.binding.ivAvatar)
        holder.binding.tvName.text = data.user!!.username
        holder.binding.tvPhone.text = data.user!!.mobile
        if (data.user!!.mobile == AccountManager.getInstancce().getLoginUserInfo()!!.mobile) {
            holder.binding.tvCurrentUse.text = "当前使用"
        } else {
            holder.binding.tvCurrentUse.text = ""
        }

        if (mItemClickListener != null) {
            holder.itemView.setOnClickListener {
                mItemClickListener!!.onAccountItemClick(data)
            }
        }
    }

    override fun getItemCount(): Int {
        return data.size
    }

    interface OnAccountListItemClickListener {
        fun onAccountItemClick(data: LoginResponse)
    }

    fun setOnAccountListItemClickListener(listener: OnAccountListItemClickListener) {
        this.mItemClickListener = listener
    }

}